package com.shuorikeji.huohuo.ui.sj;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;
import com.google.android.material.imageview.ShapeableImageView;
import com.shuorikeji.huohuo.R;
import com.shuorikeji.huohuo.adapter.MhHotTagAdapter;
import com.shuorikeji.huohuo.base.BasePresenterActivity;
import com.shuorikeji.huohuo.bean.MhHotTagInfoBean;
import com.shuorikeji.huohuo.callback.ClickCallBack;
import com.shuorikeji.huohuo.mvp.AllPresenter;
import com.shuorikeji.huohuo.utils.AndroidBug5497Workaround;
import com.shuorikeji.huohuo.utils.BusinessUtils;
import com.shuorikeji.huohuo.utils.GlideLoadEngine;
import com.shuorikeji.huohuo.utils.GsonUtil;
import com.shuorikeji.huohuo.utils.ToastShowUtil;
import com.shuorikeji.huohuo.view.GridDividerItemDecoration;
import com.luck.picture.lib.permissions.RxPermissions;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.filter.Filter;
import com.zhihu.matisse.internal.entity.CaptureStrategy;
import com.zhihu.matisse.internal.entity.IncapableCause;
import com.zhihu.matisse.internal.entity.Item;

import java.io.FileNotFoundException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.RecyclerView;
import butterknife.BindView;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;

public class CjMhSdActivity extends BasePresenterActivity<AllPresenter> {
    @BindView(R.id.iv_back)
    ImageView ivBack;
    @BindView(R.id.et_sd_title)
    EditText etSdTitle;
    @BindView(R.id.et_sd_jj)
    EditText etSdJj;
    @BindView(R.id.tv_sec_tag)
    TextView tvSecTag;
    @BindView(R.id.rv_tag)
    RecyclerView rvTag;
    @BindView(R.id.iv_sm_kg)
    ImageView ivSmKg;
    @BindView(R.id.tv_cj_sd)
    TextView tvCjSd;
    @BindView(R.id.siv_sd_fm)
    ShapeableImageView sivSdFm;
    @BindView(R.id.iv_add_fm)
    ImageView ivAddFm;

    private int smFlag;//是否私密:1=不私密,2=私密
    private List<MhHotTagInfoBean> secTagList = new ArrayList<>();
    private MhHotTagAdapter mhHotTagAdapter;
    private String tagIds;
    private List<String> imgLocalList = new ArrayList<>();
    private List<String> imgNetList = new ArrayList<>();
    private String imgNetUrl = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getmImmersionBar().reset().statusBarColor(R.color.transparent).statusBarDarkFont(true, 0.2f).init();
        AndroidBug5497Workaround.assistActivity(CjMhSdActivity.this);
    }

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_cj_mh_sd);
    }

    @Override
    protected void initData() {
        smFlag = 1;
        ivSmKg.setImageResource(R.mipmap.icon_cj_mh_sd_kg_close);
        initAdapter();
        initClick();
    }

    private void initAdapter() {
        FlexboxLayoutManager manager = new FlexboxLayoutManager(this);
        manager.setFlexDirection(FlexDirection.ROW);
        manager.setFlexWrap(FlexWrap.WRAP);
        rvTag.addItemDecoration(new GridDividerItemDecoration(20));
        rvTag.setLayoutManager(manager);
        mhHotTagAdapter = new MhHotTagAdapter(CjMhSdActivity.this, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
            }
        });
        rvTag.setAdapter(mhHotTagAdapter);
    }

    private void addMhSd() {
        mPresenter.addMhSd(true, etSdTitle.getText().toString(), etSdJj.getText().toString(), tagIds, smFlag, imgNetUrl, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        setResult(RESULT_OK);
                        finish();
                        break;
                    case 2:
                        String msg = (String) object;
                        ToastShowUtil.showToastCenter(CjMhSdActivity.this, msg);
                        break;
                }
            }
        });
    }

    private void rqTxQx(int code) {
        final String[] permissionsGroup = new String[]{
                Manifest.permission.CAMERA
                , Manifest.permission.WRITE_EXTERNAL_STORAGE
                , Manifest.permission.READ_EXTERNAL_STORAGE};
        new RxPermissions(this)
                .request(permissionsGroup)
                .subscribe(new Observer<Boolean>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                    }

                    @Override
                    public void onNext(Boolean aBoolean) {
                        Log.i("wxl", "上传头像权限申请状态：" + aBoolean);
                        if (aBoolean) {
                            secTxPhoto(code);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                    }

                    @Override
                    public void onComplete() {
                    }
                });
    }

    private void secTxPhoto(int qxCode) {
        Matisse.from(this)
                .choose(MimeType.ofImage(), false)
                .capture(true)  // 使用相机，和 captureStrategy 一起使用
                .captureStrategy(new CaptureStrategy(true, "com.ld.music.fileprovider"))
                .theme(R.style.Matisse_Dracula)
                .countable(true)
                .maxSelectable(1)
                .addFilter(new Filter() {
                    @Override
                    protected Set<MimeType> constraintTypes() {
                        return new HashSet<MimeType>() {{
                            add(MimeType.PNG);
                        }};
                    }

                    @Override
                    public IncapableCause filter(Context context, Item item) {
                        try {
                            InputStream inputStream = getContentResolver().openInputStream(item.getContentUri());
                            BitmapFactory.Options options = new BitmapFactory.Options();
                            options.inJustDecodeBounds = true;
                            BitmapFactory.decodeStream(inputStream, null, options);
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
                        return null;
                    }
                })
                .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT)
                .thumbnailScale(0.87f)
                .imageEngine(new GlideLoadEngine())
                .forResult(qxCode);
    }

    private void scPhoto() {
        BusinessUtils.upLoadPhotos(imgLocalList, new ClickCallBack() {
            @Override
            public void onClick(int flag, Object object) {
                switch (flag) {
                    case 1:
                        imgNetList.clear();
                        imgNetList = (List<String>) object;
                        imgNetUrl = imgNetList.get(0);
                        sivSdFm.setVisibility(View.VISIBLE);
                        BusinessUtils.setLoadImg(CjMhSdActivity.this, imgNetUrl, sivSdFm);
                        break;
                    case 2:
                        String msg = (String) object;
                        ToastShowUtil.showToastCenter(CjMhSdActivity.this, msg);
                        break;
                }
            }
        });
    }

    private void initClick() {
        ivBack.setOnClickListener(view -> {
            finish();
        });
        tvSecTag.setOnClickListener(view -> {
            Intent intent = new Intent(CjMhSdActivity.this, MhHotTagActivity.class);
            startActivityForResult(intent, 1001);
        });
        ivSmKg.setOnClickListener(view -> {
            if (smFlag == 1) {
                smFlag = 2;
                ivSmKg.setImageResource(R.mipmap.icon_cj_mh_sd_kg_open);
            } else {
                smFlag = 1;
                ivSmKg.setImageResource(R.mipmap.icon_cj_mh_sd_kg_close);
            }
        });
        ivAddFm.setOnClickListener(view -> {
            rqTxQx(1002);
        });
        tvCjSd.setOnClickListener(view -> {
            if (BusinessUtils.isEmpty(etSdTitle.getText().toString())) {
                ToastShowUtil.showToastCenter(CjMhSdActivity.this, "请填写书单标题");
            } else if (BusinessUtils.isEmpty(imgNetUrl)) {
                ToastShowUtil.showToastCenter(CjMhSdActivity.this, "请上传书单封面");
            } else if (BusinessUtils.isEmpty(etSdJj.getText().toString())) {
                ToastShowUtil.showToastCenter(CjMhSdActivity.this, "请填写书单简介");
            } else if (BusinessUtils.isEmpty(tagIds)) {
                ToastShowUtil.showToastCenter(CjMhSdActivity.this, "请选择标签");
            } else {
                addMhSd();
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 1001:
                    String tagStr = data.getStringExtra("SEC_TAG");
                    try {
                        secTagList = GsonUtil.fromJsonArray(tagStr, MhHotTagInfoBean.class);
                        mhHotTagAdapter.setData(secTagList);
                        if (secTagList != null && secTagList.size() > 0) {
                            String idsTemp = "";
                            for (int i = 0; i < secTagList.size(); i++) {
                                idsTemp = idsTemp + "," + secTagList.get(i).getId();
                            }
                            tagIds = BusinessUtils.getAllIds(idsTemp);
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    break;
                case 1002:
                    List<String> pathList = Matisse.obtainPathResult(data);
                    for (String pathTemp : pathList) {
                        Log.i("wxl", "上传用户头像选择的图片path：" + pathTemp);
                        imgLocalList.clear();
                        imgLocalList.add(pathTemp);
                        scPhoto();
                    }
                    break;
            }
        }
    }
}